# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

import calendar

from datetime import date

from pylons import tmpl_context as c, request, url
from pylons.controllers.util import redirect
from paste.fileapp import FileApp

from repoze.what.plugins.pylonshq import ControllerProtector
from repoze.what.predicates import in_group

from chowa.model.organization import Office

from hrms.lib.base import BaseController, render, Session
from hrms.model.person import Employee
from hrms.model.worktime import *

@ControllerProtector(in_group('hrms.administrators'))
class OfficesController(BaseController):
    def index(self):
        c.offices = Session.query(Office).all()
        return render('/hrms/worktime/offices.html')
        
    def office(self, id):
        timesheets = Session.query(Timesheet) \
            .filter_by(office_id=id).all()
        years = {}
        for timesheet in timesheets:
            if years.has_key(timesheet.year):
                years[timesheet.year] += [timesheet]
            else:
                years[timesheet.year] = [timesheet]
        
        c.years = years.items()
        c.years.sort()
        
        c.office = Session.query(Office).get(id)
        return render('/hrms/worktime/office.html')
    
    def generate(self, id):
        if request.method == 'POST':
            year = int(request.POST.get('year'))
            month = int(request.POST.get('month'))
            days_in_month = calendar.monthrange(year, month)[1]
            
            query = Session.query(Timesheet).filter_by(office_id=id)
            exists = query.filter_by(year=year, month=month).count()
            if exists:
                return redirect(url.current(action='office'))
            
            previous = query.order_by('year desc', 'month desc').first()
            timesheet = Timesheet(year=year, month=month, office_id=id)
            Session.add(timesheet)
            Session.commit()
            
            employees = Session.query(Employee) \
                .filter_by(office_id=id, is_employee=True).all()
            
            i = WorkingDay.__table__.insert()
            if previous:
                prev_data = [(e.employee_id, {'number': e.number, 'salary': e.salary})
                             for e in previous.employees]
                prev_data = dict(prev_data)
            for employee in employees:
                salary = None
                number = None
                if previous:
                    prev_empl_data = prev_data.get(employee.id)
                    if prev_empl_data:
                        salary = prev_empl_data['salary']
                        number = prev_empl_data['number']
                month = WorkingMonth(timesheet_id=timesheet.id,
                                     employee_id=employee.id,
                                     salary=salary, number=number)
                Session.add(month)
                Session.commit()
                is_weekday = lambda day: date(timesheet.year, timesheet.month, day).weekday() < 5
                hours = lambda day: 8 if is_weekday(day) else None
                code = lambda day: 1 if is_weekday(day) else None
                values = [dict(month_id=month.id, day=day, hours=hours(day), code_id=code(day))
                          for day in range(1, days_in_month+1)]
                Session.execute(i, values)
        return redirect(url.current(action='office'))
